package com.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory.ConfirmType;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {
    private static final Logger log = LoggerFactory.getLogger(RabbitMQConfig.class);
    @Autowired
    private CachingConnectionFactory connectionFactory;
    @Value("${rabbit.queueName}")
    String queueName;
    @Value("${rabbit.exchangeName}")
    String exchangeName;
    @Value("${rabbit.routingKey}")
    String routingKey;

    public RabbitMQConfig() {
    }

    @Bean
    public Queue initQueue() {
        return new Queue(this.queueName);
    }

    @Bean
    public DirectExchange initDirectExchange() {
        return new DirectExchange(this.exchangeName);
    }

    @Bean
    public Binding bindingDirect() {
        return BindingBuilder.bind(this.initQueue()).to(this.initDirectExchange()).with(this.routingKey);
    }

    @Bean
    public RabbitTemplate rabbitTemplate() {
        this.connectionFactory.setPublisherConfirmType(ConfirmType.CORRELATED);
        this.connectionFactory.setPublisherReturns(true);
        RabbitTemplate rabbitTemplate = new RabbitTemplate(this.connectionFactory);
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                if (ack) {
                    RabbitMQConfig.log.info("消息发送成功");
                } else {
                    RabbitMQConfig.log.info("消息发送失败,原因: {}", cause);
                }

            }
        });
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            public void returnedMessage(ReturnedMessage message) {
                RabbitMQConfig.log.info("消息发送失败: {}", message);
            }
        });
        return rabbitTemplate;
    }
}
